package other.xsy.baidu;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.Lead;
import com.rkhd.platform.sdk.data.model.Opportunity;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.xsy.baidu.util.HCDateUtils;
import other.xsy.baidu.util.HCXObjectService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 创建销售线索前: 判断来源是公众号的进行人员分配
 * @Author 黎炎松
 * 2024-06-06 14:30
 */
public class LeadAddBeforeTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    protected XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "创建销售线索前: 判断来源是公众号的进行人员分配 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Lead> leadLista = new ArrayList<>();
        for (XObject xObject : dataList) {
            Lead lead = (Lead) xObject;
            leadLista.add(lead);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        dataResultList.set(0, upLeadOwnerUser(leadLista.get(0)));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) throws ApiEntityServiceException {

    }

    /**
     * 修改销售线索的所有人
     * @param lead
     */
    public DataResult upLeadOwnerUser(Lead lead){
        try {
            logger.debug(LOGGER_MSG + " 处理开始:" + lead);

            // 首先判断来源是否是公众号
            Integer dataSource = lead.getDataSource__c();
            if (!Objects.equals(dataSource, 5)) {
                logger.debug(LOGGER_MSG + "数据来源不是公众号，无需处理");
                return new DataResult(true,"" , lead);
            }

            // 从数据配置表中获取数据
            String sql = "select id,lastSyncTime__c,syncAssistVal__c from syncConfig__c where syncKey__c = 'GZH_SYSFP'";
            SyncConfig__c syncConfig = hcxObjectService.queryOne(sql, SyncConfig__c.class);
            if (syncConfig == null) {
                logger.debug(LOGGER_MSG + "数据配置信息不存在");
                return new DataResult(true,"" , lead);
            }

            String dealDate = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME);

            // 查询分配客户数据
            sql = "select id,name,dimDepart from user where status = 1 and assignBdAccount__c in (5) order by createdAt";
            QueryResult<JSONObject> xoqlQuery = xoqlService.query(sql);
            List<JSONObject> userList = xoqlQuery.getRecords();
            logger.debug(LOGGER_MSG + " userList " + userList);
            if (xoqlQuery.getTotalCount() <= 0 ) {
                logger.debug(LOGGER_MSG + "无分配用户数据");
                return new DataResult(true,"" , lead);
            }

            // 初始化下标 用来记录当前分配的用户下标
            String lastUserId = syncConfig.getSyncAssistVal__c();
            int userListActIndex = 0;
            if (StringUtils.isNotBlank(lastUserId) && userList.size() > 1) {
                int index = userList.stream().map(v -> v.getString("id")).collect(Collectors.toList()).indexOf(lastUserId);
                userListActIndex = index != -1 ? index : 0;
            }

            // 赋值 （需要复制所需部门 ）
            lead.setOwnerId(userList.get(userListActIndex).getLong("id"));
            lead.setDimDepart(userList.get(userListActIndex).getLong("dimDepart"));
            userListActIndex++;
            if (userListActIndex == userList.size()) {
                userListActIndex = 0;
            }

            // 更新配置表信息
            syncConfig.setLastSyncTime__c(dealDate);
            // 用来记录下次分配开始的用户
            syncConfig.setSyncAssistVal__c(userList.get(userListActIndex).getString("id"));
            hcxObjectService.update(syncConfig);

            logger.debug(LOGGER_MSG + "分配用户成功");
            return new DataResult(true,"" , lead);
        } catch (Exception e) {
            logger.debug(LOGGER_MSG + " 处理异常:" + e.getMessage());
            return new DataResult(false, "新增异常", lead);
        }
    }

}
